package com.xuantu.learn.springsession2.interceptor;

import java.util.Set;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import lombok.Getter;
import lombok.Setter;

public class AuthInterceptor extends HandlerInterceptorAdapter {

    /**
     * 排除url,不拦截
     */
    @Getter
    @Setter
    private Set<String> excludeUrls;

    @Getter
    @Setter
    private Set<String> includeUrls;

    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = request.getRequestURL().toString();
        logger.debug("请求URL：{}",url);
        String uri = request.getRequestURI();
        logger.debug("请求URI：{}",uri);
        String query = request.getQueryString();
        logger.debug("请求参数：{}",query);

        String requestPath = uri.substring(request.getContextPath().length() + 1);// 去掉项目路径

        Pattern pattern = null;
        for(String str : excludeUrls){
            pattern = Pattern.compile(str);
            if(pattern.matcher(requestPath).matches()){
                return true;
            }
        }

        boolean accessFlag = false;
        for(String str : includeUrls){
            pattern = Pattern.compile(str);
            if(pattern.matcher(requestPath).matches()){
                accessFlag = true;
                break;
            }
        }

        if(accessFlag || includeUrls == null || includeUrls.isEmpty()){
        	Object sessionUser = WebUtils.getSessionAttribute(request, "USER");
            if (sessionUser == null) {
                ModelAndView modelAndView = new ModelAndView("redirect:/login");
                if (query != null){
                    logger.debug("拦截请求路径{}?{}",uri,query);
                    modelAndView.addObject("returnUrl", uri + "?" + query);
                } else {
                    modelAndView.addObject("returnUrl", uri);
                }
                //return false;
                throw new ModelAndViewDefiningException(modelAndView);
            }else{
                return true;
            }
        }else{
            return true;
        }
    }

}
